<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="80px"
    >
      <el-form-item label="目录id" prop="cateId">
        <el-input
          v-model="queryParams.cateId"
          placeholder="请输入目录id"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属单位" prop="tenantId">
        <el-input
          v-model="queryParams.tenantId"
          placeholder="请输入所属单位"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="数据源名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入数据源名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="数据源编码" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入数据源编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="数据库schema" prop="schema">
        <el-input
          v-model="queryParams.schema"
          placeholder="请输入数据库schema"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="数据库用户名" prop="username">
        <el-input
          v-model="queryParams.username"
          placeholder="请输入数据库用户名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="驱动类型" prop="driverClassName">
        <el-input
          v-model="queryParams.driverClassName"
          placeholder="请输入驱动类型"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="连接池初始大小" prop="initialSize">
        <el-input
          v-model="queryParams.initialSize"
          placeholder="请输入连接池初始大小"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="连接池最小连接数" prop="minIdle">
        <el-input
          v-model="queryParams.minIdle"
          placeholder="请输入连接池最小连接数"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="连接池最大连接数" prop="maxActive">
        <el-input
          v-model="queryParams.maxActive"
          placeholder="请输入连接池最大连接数"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="获取连接超时时间（ms）" prop="maxWait">
        <el-input
          v-model="queryParams.maxWait"
          placeholder="请输入获取连接超时时间（ms）"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="空闲检测时间间隔（ms）" prop="timeBetweenEvictionRuns">
        <el-input
          v-model="queryParams.timeBetweenEvictionRuns"
          placeholder="请输入空闲检测时间间隔（ms）"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="连接最小生存时间（ms）" prop="minEvictableIdleTime">
        <el-input
          v-model="queryParams.minEvictableIdleTime"
          placeholder="请输入连接最小生存时间（ms）"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="连接最大生存时间（ms）" prop="maxEvictableIdleTime">
        <el-input
          v-model="queryParams.maxEvictableIdleTime"
          placeholder="请输入连接最大生存时间（ms）"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="空闲时检测" prop="testWhileIdle">
        <el-input
          v-model="queryParams.testWhileIdle"
          placeholder="请输入空闲时检测"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="获取时检测" prop="testOnBorrow">
        <el-input
          v-model="queryParams.testOnBorrow"
          placeholder="请输入获取时检测"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用完时检测" prop="testOnReturn">
        <el-input
          v-model="queryParams.testOnReturn"
          placeholder="请输入用完时检测"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="描述" prop="remark">
        <el-input
          v-model="queryParams.remark"
          placeholder="请输入描述"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['web:data:query:sdkDqDs:add']"
        >
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate({})"
          v-hasPermi="['web:data:query:sdkDqDs:edit']"
        >
          修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete({})"
          v-hasPermi="['web:data:query:sdkDqDs:remove']"
        >
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Upload"
          @click="handleImport"
          v-hasPermi="['web:data:query:sdkDqDs:import']"
        >
          导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['web:data:query:sdkDqDs:export']"
        >
          导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @query-table="getList" />
    </el-row>

    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="目录id" align="center" prop="cateId" />
      <el-table-column label="所属单位" align="center" prop="tenantId" />
      <el-table-column label="数据源名称" align="center" prop="name" />
      <el-table-column label="数据源编码" align="center" prop="code" />
      <el-table-column label="数据库schema" align="center" prop="schema" />
      <el-table-column label="数据源类型" align="center" prop="dataSourceType" />
      <el-table-column label="jdbc链接" align="center" prop="jdbcUrl" />
      <el-table-column label="数据库用户名" align="center" prop="username" />
      <el-table-column label="数据库密码" align="center" prop="password" />
      <el-table-column label="驱动类型" align="center" prop="driverClassName" />
      <el-table-column label="连接池初始大小" align="center" prop="initialSize" />
      <el-table-column label="连接池最小连接数" align="center" prop="minIdle" />
      <el-table-column label="连接池最大连接数" align="center" prop="maxActive" />
      <el-table-column label="获取连接超时时间（ms）" align="center" prop="maxWait" />
      <el-table-column
        label="空闲检测时间间隔（ms）"
        align="center"
        prop="timeBetweenEvictionRuns"
      />
      <el-table-column label="连接最小生存时间（ms）" align="center" prop="minEvictableIdleTime" />
      <el-table-column label="连接最大生存时间（ms）" align="center" prop="maxEvictableIdleTime" />
      <el-table-column label="连接检测sql" align="center" prop="validationQuery" />
      <el-table-column label="空闲时检测" align="center" prop="testWhileIdle" />
      <el-table-column label="获取时检测" align="center" prop="testOnBorrow" />
      <el-table-column label="用完时检测" align="center" prop="testOnReturn" />
      <el-table-column label="描述" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['web:data:query:sdkDqDs:edit']"
          >
            修改
          </el-button>
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['web:data:query:sdkDqDs:remove']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="pageParams.pageNum"
      v-model:limit="pageParams.pageSize"
      @pagination="getList"
    />

    <el-dialog
      :title="title"
      v-model="open"
      width="500px"
      append-to-body
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="目录id" prop="cateId">
          <el-input v-model="form.cateId" placeholder="请输入目录id" />
        </el-form-item>
        <el-form-item label="所属单位" prop="tenantId">
          <el-input v-model="form.tenantId" placeholder="请输入所属单位" />
        </el-form-item>
        <el-form-item label="数据源名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入数据源名称" />
        </el-form-item>
        <el-form-item label="数据源编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入数据源编码" />
        </el-form-item>
        <el-form-item label="数据库schema" prop="schema">
          <el-input v-model="form.schema" placeholder="请输入数据库schema" />
        </el-form-item>
        <el-form-item label="数据源类型" prop="dataSourceType">
          <el-select v-model="form.dataSourceType" placeholder="请选择数据源类型">
            <el-option label="请选择字典生成" value="" />
          </el-select>
        </el-form-item>
        <el-form-item label="jdbc链接" prop="jdbcUrl">
          <el-input v-model="form.jdbcUrl" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="数据库用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入数据库用户名" />
        </el-form-item>
        <el-form-item label="数据库密码" prop="password">
          <el-input v-model="form.password" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="驱动类型" prop="driverClassName">
          <el-input v-model="form.driverClassName" placeholder="请输入驱动类型" />
        </el-form-item>
        <el-form-item label="连接池初始大小" prop="initialSize">
          <el-input v-model="form.initialSize" placeholder="请输入连接池初始大小" />
        </el-form-item>
        <el-form-item label="连接池最小连接数" prop="minIdle">
          <el-input v-model="form.minIdle" placeholder="请输入连接池最小连接数" />
        </el-form-item>
        <el-form-item label="连接池最大连接数" prop="maxActive">
          <el-input v-model="form.maxActive" placeholder="请输入连接池最大连接数" />
        </el-form-item>
        <el-form-item label="获取连接超时时间（ms）" prop="maxWait">
          <el-input v-model="form.maxWait" placeholder="请输入获取连接超时时间（ms）" />
        </el-form-item>
        <el-form-item label="空闲检测时间间隔（ms）" prop="timeBetweenEvictionRuns">
          <el-input
            v-model="form.timeBetweenEvictionRuns"
            placeholder="请输入空闲检测时间间隔（ms）"
          />
        </el-form-item>
        <el-form-item label="连接最小生存时间（ms）" prop="minEvictableIdleTime">
          <el-input
            v-model="form.minEvictableIdleTime"
            placeholder="请输入连接最小生存时间（ms）"
          />
        </el-form-item>
        <el-form-item label="连接最大生存时间（ms）" prop="maxEvictableIdleTime">
          <el-input
            v-model="form.maxEvictableIdleTime"
            placeholder="请输入连接最大生存时间（ms）"
          />
        </el-form-item>
        <el-form-item label="连接检测sql" prop="validationQuery">
          <el-input v-model="form.validationQuery" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="空闲时检测" prop="testWhileIdle">
          <el-input v-model="form.testWhileIdle" placeholder="请输入空闲时检测" />
        </el-form-item>
        <el-form-item label="获取时检测" prop="testOnBorrow">
          <el-input v-model="form.testOnBorrow" placeholder="请输入获取时检测" />
        </el-form-item>
        <el-form-item label="用完时检测" prop="testOnReturn">
          <el-input v-model="form.testOnReturn" placeholder="请输入用完时检测" />
        </el-form-item>
        <el-form-item label="描述" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      :title="upload.title"
      v-model="upload.open"
      width="400px"
      append-to-body
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload">
          <upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />
              是否更新已经存在的数据查询-数据源数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate"
              >下载模板
            </el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
  import { ref } from 'vue';
  import {
    pageSdkDqDs,
    getSdkDqDsInfo,
    addSdkDqDs,
    updateSdkDqDs,
    delSdkDqDs,
    tplSdkDqDs,
    exportSdkDqDs,
  } from '@/api/web/db/dataquery/sdkDqDs';
  import { getToken } from '@/utils/auth';
  // import { parseTime, addFieldTimeRange, addFieldDateRange } from '@/utils/base';
  // import { useDict } from '@/utils/dict';
  import modal from '@/plugins/modal';

  // const {} = useDict();

  const pageParams = ref({
    pageNum: 1,
    pageSize: 10,
  });
  const queryParams = ref({
    cateId: null,
    tenantId: null,
    name: null,
    code: null,
    schema: null,
    dataSourceType: null,
    jdbcUrl: null,
    username: null,
    password: null,
    driverClassName: null,
    initialSize: null,
    minIdle: null,
    maxActive: null,
    maxWait: null,
    timeBetweenEvictionRuns: null,
    minEvictableIdleTime: null,
    maxEvictableIdleTime: null,
    validationQuery: null,
    testWhileIdle: null,
    testOnBorrow: null,
    testOnReturn: null,
    remark: null,
  });
  const queryRef = ref(null);
  const list = ref([]);
  const open = ref(false);
  const loading = ref(false);
  const showSearch = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const title = ref('');

  const uploadRef = ref(null);
  const upload = ref({
    open: false,
    title: '',
    isUploading: false,
    updateSupport: 0,
    headers: { Authorization: 'Bearer ' + getToken() },
    url: import.meta.env.VITE_APP_BASE_API + '/web/data/query/sdkDqDs/import',
  });

  const formRef = ref(null);
  const form = ref({});
  const rules = ref({
    id: [
      {
        required: true,
        message: '主键不能为空',
        trigger: 'blur',
      },
    ],
    tenantId: [
      {
        min: 0,
        max: 64,
        message: '所属单位长度必须介于 0 和 64 之间',
        trigger: 'blur',
      },
    ],
    name: [
      {
        min: 0,
        max: 64,
        message: '数据源名称长度必须介于 0 和 64 之间',
        trigger: 'blur',
      },
    ],
    code: [
      {
        min: 0,
        max: 64,
        message: '数据源编码长度必须介于 0 和 64 之间',
        trigger: 'blur',
      },
    ],
    schema: [
      {
        min: 0,
        max: 64,
        message: '数据库schema长度必须介于 0 和 64 之间',
        trigger: 'blur',
      },
    ],
    dataSourceType: [
      {
        min: 0,
        max: 255,
        message: '数据源类型长度必须介于 0 和 255 之间',
        trigger: 'change',
      },
    ],
    jdbcUrl: [
      {
        min: 0,
        max: 1024,
        message: 'jdbc链接长度必须介于 0 和 1024 之间',
        trigger: 'blur',
      },
    ],
    username: [
      {
        min: 0,
        max: 255,
        message: '数据库用户名长度必须介于 0 和 255 之间',
        trigger: 'blur',
      },
    ],
    password: [
      {
        min: 0,
        max: 1000,
        message: '数据库密码长度必须介于 0 和 1000 之间',
        trigger: 'blur',
      },
    ],
    driverClassName: [
      {
        min: 0,
        max: 255,
        message: '驱动类型长度必须介于 0 和 255 之间',
        trigger: 'blur',
      },
    ],
    validationQuery: [
      {
        min: 0,
        max: 1024,
        message: '连接检测sql长度必须介于 0 和 1024 之间',
        trigger: 'blur',
      },
    ],
    testWhileIdle: [
      {
        min: 0,
        max: 16,
        message: '空闲时检测长度必须介于 0 和 16 之间',
        trigger: 'blur',
      },
    ],
    testOnBorrow: [
      {
        min: 0,
        max: 16,
        message: '获取时检测长度必须介于 0 和 16 之间',
        trigger: 'blur',
      },
    ],
    testOnReturn: [
      {
        min: 0,
        max: 16,
        message: '用完时检测长度必须介于 0 和 16 之间',
        trigger: 'blur',
      },
    ],
    remark: [
      {
        min: 0,
        max: 255,
        message: '描述长度必须介于 0 和 255 之间',
        trigger: 'blur',
      },
    ],
  });

  function getList() {
    loading.value = true;
    pageSdkDqDs(pageParams.value, queryParams.value)
      .then((res) => {
        list.value = res?.data?.records ?? [];
        total.value = res?.data?.total ?? 0;
      })
      .finally(() => {
        loading.value = false;
      });
  }

  function cancel() {
    open.value = false;
    reset();
  }

  function reset() {
    form.value = {
      id: null,
      cateId: null,
      tenantId: null,
      name: null,
      code: null,
      schema: null,
      dataSourceType: null,
      jdbcUrl: null,
      username: null,
      password: null,
      driverClassName: null,
      initialSize: null,
      minIdle: null,
      maxActive: null,
      maxWait: null,
      timeBetweenEvictionRuns: null,
      minEvictableIdleTime: null,
      maxEvictableIdleTime: null,
      validationQuery: null,
      testWhileIdle: null,
      testOnBorrow: null,
      testOnReturn: null,
      createTime: null,
      createBy: null,
      updateTime: null,
      updateBy: null,
      remark: null,
      userId: null,
      deptId: null,
    };
    formRef.value?.resetFields();
  }

  function handleQuery() {
    pageParams.value.pageNum = 1;
    getList();
  }

  function resetQuery() {
    queryRef.value?.resetFields();
    handleQuery();
  }

  function handleSelectionChange(selection) {
    ids.value = selection.map((item) => item.id);
    single.value = selection.length !== 1;
    multiple.value = !selection.length;
  }

  function handleAdd() {
    reset();
    title.value = '添加数据查询-数据源';
    open.value = true;
  }

  function handleUpdate(row) {
    reset();
    const _id = row?.id ?? ids.value[0];
    getSdkDqDsInfo(_id).then((res) => {
      form.value = res.data;
      title.value = '修改数据查询-数据源';
      open.value = true;
    });
  }

  function submitForm() {
    formRef.value.validate((valid) => {
      if (valid) {
        if (form.value.id) {
          updateSdkDqDs(form.value).then(() => {
            modal.msgSuccess('修改成功');
            open.value = false;
            getList();
          });
        } else {
          addSdkDqDs(form.value).then(() => {
            modal.msgSuccess('新增成功');
            open.value = false;
            getList();
          });
        }
      }
    });
  }

  function handleDelete(row) {
    const _ids = row?.id ?? ids.value.join(',');
    modal
      .confirm('是否确认删除数据查询-数据源编号为"' + _ids + '"的数据项？')
      .then(() => {
        return delSdkDqDs(_ids);
      })
      .then(() => {
        getList();
        modal.msgSuccess('删除成功');
      })
      .catch(() => {});
  }

  function handleExport() {
    exportSdkDqDs(pageParams.value, queryParams.value);
  }

  function handleImport() {
    upload.value.title = '数据查询-数据源导入';
    upload.value.open = true;
  }

  function importTemplate() {
    tplSdkDqDs();
  }

  function handleFileUploadProgress() {
    upload.value.isUploading = true;
  }

  function handleFileSuccess(res, file) {
    upload.value.open = false;
    upload.value.isUploading = false;
    uploadRef.value.handleRemove(file);
    modal.msgSuccess(res.msg);
    getList();
  }

  function submitFileForm() {
    uploadRef.value.submit();
  }

  getList();
</script>
